{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a8b892c8",
   "metadata": {},
   "source": [
    "Printed and electronic copies of *Modeling and Simulation in Python* are available from [No Starch Press](https://nostarch.com/modeling-and-simulation-python) and [Bookshop.org](https://bookshop.org/p/books/modeling-and-simulation-in-python-allen-b-downey/17836697?ean=9781718502161) and [Amazon](https://amzn.to/3y9UxNb)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "wicked-mozambique",
   "metadata": {},
   "source": [
    "# World Population"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "imported-table",
   "metadata": {
    "tags": []
   },
   "source": [
    "*Modeling and Simulation in Python*\n",
    "\n",
    "Copyright 2021 Allen Downey\n",
    "\n",
    "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "electoral-turkey",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# install Pint if necessary\n",
    "\n",
    "try:\n",
    "    import pint\n",
    "except ImportError:\n",
    "    !pip install pint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "formal-context",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# download modsim.py if necessary\n",
    "\n",
    "from os.path import basename, exists\n",
    "\n",
    "def download(url):\n",
    "    filename = basename(url)\n",
    "    if not exists(filename):\n",
    "        from urllib.request import urlretrieve\n",
    "        local, _ = urlretrieve(url, filename)\n",
    "        print('Downloaded ' + local)\n",
    "    \n",
    "download('https://raw.githubusercontent.com/AllenDowney/' +\n",
    "         'ModSimPy/master/modsim.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "progressive-typing",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import functions from modsim\n",
    "\n",
    "from modsim import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "informal-contractor",
   "metadata": {},
   "source": [
    "In 1968 Paul Erlich published *The Population Bomb*, in which he\n",
    "predicted that world population would grow quickly during the 1970s,\n",
    "that agricultural production could not keep up, and that mass starvation in the next two decades was inevitable (see\n",
    "<https://modsimpy.com/popbomb>). As someone who grew up during those\n",
    "decades, I am happy to report that those predictions were wrong.\n",
    "\n",
    "But world population growth is still a topic of concern, and it is an\n",
    "open question how many people Earth can sustain while maintaining\n",
    "and improving our quality of life.\n",
    "\n",
    "In this chapter and the next, we use tools from the previous chapters to model world population growth since 1950 and generate predictions for the next 50-100 years.\n",
    "For background on world population growth, watch this video from the\n",
    "American Museum of Natural History <https://modsimpy.com/human>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "plastic-trigger",
   "metadata": {},
   "source": [
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "Click here to access the notebooks: <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dying-browse",
   "metadata": {},
   "source": [
    "## World Population Growth\n",
    "\n",
    "The Wikipedia article on world population contains tables with estimates of world population from prehistory to the present, and projections for the future (<https://modsimpy.com/worldpop>)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "continuing-cancellation",
   "metadata": {
    "tags": []
   },
   "source": [
    "The following cell downloads a copy of https://en.wikipedia.org/wiki/World_population_estimates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "convenient-stroke",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "download('https://raw.githubusercontent.com/AllenDowney/' +\n",
    "         'ModSimPy/master/data/World_population_estimates.html')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acknowledged-bracelet",
   "metadata": {},
   "source": [
    "To read this data, we will use the Pandas library, which provides functions for\n",
    "working with data. The function we'll use is `read_html`, which can read a web page and extract data from any tables it contains. Before we can use it, we have to import it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "israeli-finding",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pandas import read_html"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "regulation-parade",
   "metadata": {},
   "source": [
    "Now we can use it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "instant-beverage",
   "metadata": {},
   "outputs": [],
   "source": [
    "filename = 'World_population_estimates.html'\n",
    "tables = read_html(filename,\n",
    "                   header=0, \n",
    "                   index_col=0,\n",
    "                   decimal='M')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dried-immunology",
   "metadata": {},
   "source": [
    "The arguments are:\n",
    "\n",
    "-   `filename`: The name of the file (including the directory it's in)\n",
    "    as a string. This argument can also be a URL starting with `http`.\n",
    "\n",
    "-   `header`: Indicates which row of each table should be considered the\n",
    "    *header*, that is, the set of labels that identify the columns. In\n",
    "    this case it is the first row (numbered 0).\n",
    "\n",
    "-   `index_col`: Indicates which column of each table should be\n",
    "    considered the *index*, that is, the set of labels that identify\n",
    "    the rows. In this case it is the first column, which contains the\n",
    "    years.\n",
    "\n",
    "-   `decimal`: Normally this argument is used to indicate which\n",
    "    character should be considered a decimal point, because some\n",
    "    conventions use a period and some use a comma. In this case I am\n",
    "    abusing the feature by treating `M` as a decimal point, which allows\n",
    "    some of the estimates, which are expressed in millions, to be read\n",
    "    as numbers.\n",
    "\n",
    "The result, which is assigned to `tables`, is a sequence that contains\n",
    "one `DataFrame` for each table. A `DataFrame` is an object, defined by\n",
    "Pandas, that represents tabular data.\n",
    "\n",
    "To select a `DataFrame` from `tables`, we can use the bracket operator\n",
    "like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "driving-wrapping",
   "metadata": {},
   "outputs": [],
   "source": [
    "table2 = tables[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "simplified-convert",
   "metadata": {},
   "source": [
    "This line selects the third table (numbered 2), which contains\n",
    "population estimates from 1950 to 2016.\n",
    "\n",
    "We can use `head` to display the first few lines of the table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "running-alcohol",
   "metadata": {},
   "outputs": [],
   "source": [
    "table2.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "valid-editing",
   "metadata": {},
   "source": [
    "The first column, which is labeled `Year`, is special.  It is the *index* for this `DataFrame`, which means it contains the labels for the rows.\n",
    "\n",
    "Some of the values use scientific notation; for example, `2.516000e+09` is shorthand for $2.516 \\cdot 10^9$ or 2.516 billion.\n",
    "\n",
    "`NaN` is a special value that indicates missing data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "plastic-senate",
   "metadata": {},
   "source": [
    "The column labels are long strings, which makes them hard to work with.\n",
    "We can replace them with shorter strings like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "engaging-regular",
   "metadata": {},
   "outputs": [],
   "source": [
    "table2.columns = ['census', 'prb', 'un', 'maddison', \n",
    "                  'hyde', 'tanton', 'biraben', 'mj', \n",
    "                  'thomlinson', 'durand', 'clark']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "communist-crowd",
   "metadata": {},
   "source": [
    "Now we can select a column from the `DataFrame` using the dot operator,\n",
    "like selecting a state variable from a `State` object.\n",
    "\n",
    "Here are the estimates from the United States Census Bureau:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "amended-negative",
   "metadata": {},
   "outputs": [],
   "source": [
    "census = table2.census / 1e9"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "absent-heart",
   "metadata": {},
   "source": [
    "The result is a Pandas `Series`, which is similar to the `TimeSeries` and `SweepSeries` objects we've been using.\n",
    "\n",
    "The number `1e9` is a shorter way to write `1000000000` or one billion.\n",
    "When we divide a `Series` by a number, it divides all of the elements of the `Series`.\n",
    "From here on, we'll express population estimates in terms of billions.\n",
    "\n",
    "We can use `tail` to see the last few elements of the `Series`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "graduate-specialist",
   "metadata": {},
   "outputs": [],
   "source": [
    "census.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "brilliant-brook",
   "metadata": {},
   "source": [
    "The left column is the *index* of the `Series`; in this example it contains the dates.\n",
    "The right column contains the *values*, which are population estimates.\n",
    "In 2016 the world population was about 7.3 billion.\n",
    "\n",
    "Here are the estimates from the United Nations\n",
    "Department of Economic and Social Affairs (U.N. DESA):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "linear-admission",
   "metadata": {},
   "outputs": [],
   "source": [
    "un = table2.un / 1e9\n",
    "un.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "mental-sussex",
   "metadata": {},
   "source": [
    "The most recent estimate we have from the U.N. is for 2015, so the value for 2016 is `NaN`.\n",
    "\n",
    "Now we can plot the estimates like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ordered-garage",
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_estimates():\n",
    "    census.plot(style=':', label='US Census')\n",
    "    un.plot(style='--', label='UN DESA')\n",
    "    decorate(xlabel='Year', \n",
    "             ylabel='World population (billions)') "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "invisible-mouse",
   "metadata": {},
   "source": [
    "The keyword argument `style=':'` specifies a dotted line; `style='--'` specifies a dashed line.\n",
    "The `label` argument provides the string that appears in the legend.\n",
    "\n",
    "And here's what it looks like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "periodic-weekend",
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_estimates()\n",
    "decorate(title='World population estimates')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "labeled-magic",
   "metadata": {},
   "source": [
    "The lines overlap almost completely, but the most recent estimates diverge slightly.\n",
    "In the next section, we'll quantify these differences."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "tender-summer",
   "metadata": {},
   "source": [
    "## Absolute and Relative Errors\n",
    "\n",
    "Estimates of world population from the U.S. Census and the U.N. DESA differ slightly.\n",
    "One way to characterize this difference is *absolute error*, which is the absolute value of the difference between the estimates.\n",
    "\n",
    "To compute absolute errors, we can import `abs` from NumPy:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "secondary-player",
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import abs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "frozen-scotland",
   "metadata": {},
   "source": [
    "And use it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "caring-garlic",
   "metadata": {},
   "outputs": [],
   "source": [
    "abs_error = abs(un - census)\n",
    "abs_error.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bridal-extraction",
   "metadata": {},
   "source": [
    "When you subtract two `Series` objects, the result is a new `Series`.\n",
    "Because one of the estimates for 2016 is `NaN`, the result for 2016 is `NaN`.\n",
    "\n",
    "To summarize the results, we can compute the *mean absolute error*."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "corresponding-emerald",
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import mean\n",
    "\n",
    "mean(abs_error)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "identical-archive",
   "metadata": {},
   "source": [
    "On average, the estimates differ by about 0.029 billion.\n",
    "But we can also use `max` to compute the maximum absolute error."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "headed-witch",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "from numpy import max\n",
    "\n",
    "max(abs_error)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "composite-partnership",
   "metadata": {},
   "source": [
    "In the worst case, they differ by about 0.1 billion.\n",
    "\n",
    "Now 0.1 billion is a lot of people, so that might sound like a serious discrepancy.\n",
    "But counting everyone is the world is hard, and we should not expect the estimates to be exact.\n",
    "\n",
    "Another way to quantify the magnitude of the difference is *relative error*, which is the size of the error divided by the estimates themselves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "advisory-complex",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "rel_error = 100 * abs_error / census\n",
    "rel_error.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "greater-register",
   "metadata": {},
   "source": [
    "I multiplied by 100 so we can interpret the results as a percentage.  In 2015, the difference between the estimates is about 1.4%, and that happens to be the maximum.\n",
    "\n",
    "Again, we can summarize the results by computing the mean."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "frank-owner",
   "metadata": {},
   "outputs": [],
   "source": [
    "mean(rel_error)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "peaceful-fleece",
   "metadata": {},
   "source": [
    "The mean relative error is about 0.6%.\n",
    "So that's not bad.\n",
    "\n",
    "You might wonder why I divided by `census` rather than `un`.\n",
    "In general, if you think one estimate is better than the other, you put the better one in the denominator.\n",
    "In this case, I don't know which is better, so I put the smaller one in the denominator, which makes the computed errors a little bigger."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "vietnamese-excuse",
   "metadata": {},
   "source": [
    "## Modeling Population Growth\n",
    "\n",
    "Suppose we want to predict world population growth over the next 50 or\n",
    "100 years. We can do that by developing a model that describes how\n",
    "populations grow, fitting the model to the data we have so far, and then using the model to generate predictions.\n",
    "\n",
    "In the next few sections I demonstrate this process starting with simple models and gradually improving them.\n",
    "\n",
    "Although there is some curvature in the plotted estimates, it looks like world population growth has been close to linear since 1960 or so. So we'll start with a model that has constant growth.\n",
    "\n",
    "To fit the model to the data, we'll compute the average annual growth\n",
    "from 1950 to 2016. Since the UN and Census data are so close, we'll use the Census data.\n",
    "\n",
    "We can select a value from a `Series` using the bracket operator:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "undefined-sauce",
   "metadata": {},
   "outputs": [],
   "source": [
    "census[1950]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "precise-correlation",
   "metadata": {},
   "source": [
    "So we can get the total growth during the interval like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "postal-debate",
   "metadata": {},
   "outputs": [],
   "source": [
    "total_growth = census[2016] - census[1950]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dutch-sample",
   "metadata": {},
   "source": [
    "In this example, the labels 2016 and 1950 are part of the data, so it\n",
    "would be better not to make them part of the program. \n",
    "Putting values like these in the program is called *hard coding*; it is considered bad practice because if the data change in the future, we have to change the program (see <https://modsimpy.com/hardcode>).\n",
    "\n",
    "It would be better to get the labels from the `Series`.\n",
    "We can do that by selecting the index from `census` and then selecting the first element."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "functional-trick",
   "metadata": {},
   "outputs": [],
   "source": [
    "t_0 = census.index[0]\n",
    "t_0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "empty-siemens",
   "metadata": {},
   "source": [
    "So `t_0` is the label of the first element, which is 1950.\n",
    "We can get the label of the last element like this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "acoustic-south",
   "metadata": {},
   "outputs": [],
   "source": [
    "t_end = census.index[-1]\n",
    "t_end"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "express-metallic",
   "metadata": {},
   "source": [
    "The value `-1` indicates the last element; `-2` indicates the second to last element, and so on.\n",
    "\n",
    "The difference between `t_0` and `t_end` is the elapsed time between them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "planned-remains",
   "metadata": {},
   "outputs": [],
   "source": [
    "elapsed_time = t_end - t_0\n",
    "elapsed_time"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bridal-royal",
   "metadata": {},
   "source": [
    "Now we can use `t_0` and `t_end` to select the population at the beginning and end of the interval."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "quarterly-aggregate",
   "metadata": {},
   "outputs": [],
   "source": [
    "p_0 = census[t_0]\n",
    "p_end = census[t_end]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "driven-castle",
   "metadata": {},
   "source": [
    "And compute the total growth during the interval."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "prescription-optics",
   "metadata": {},
   "outputs": [],
   "source": [
    "total_growth = p_end - p_0\n",
    "total_growth"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "accepted-auditor",
   "metadata": {},
   "source": [
    "Finally, we can compute average annual growth."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "convertible-patch",
   "metadata": {},
   "outputs": [],
   "source": [
    "annual_growth = total_growth / elapsed_time\n",
    "annual_growth"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "japanese-merit",
   "metadata": {},
   "source": [
    "From 1950 to 2016, world population grew by about 0.07 billion people per year, on average.\n",
    "The next step is to use this estimate to simulate population growth."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "public-verification",
   "metadata": {},
   "source": [
    "## Simulating Population Growth\n",
    "\n",
    "Our simulation will start with the observed population in 1950, `p_0`,\n",
    "and add `annual_growth` each year. To store the results, we'll use a\n",
    "`TimeSeries` object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "duplicate-leave",
   "metadata": {},
   "outputs": [],
   "source": [
    "results = TimeSeries()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "expired-salmon",
   "metadata": {},
   "source": [
    "We can set the first value in the new `TimeSeries` like this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "convenient-thong",
   "metadata": {},
   "outputs": [],
   "source": [
    "results[t_0] = p_0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "constant-casino",
   "metadata": {},
   "source": [
    "Here's what it looks like so far."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "israeli-surveillance",
   "metadata": {},
   "outputs": [],
   "source": [
    "show(results)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "stretch-snapshot",
   "metadata": {},
   "source": [
    "Now we set the rest of the values by simulating annual growth:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "attended-morris",
   "metadata": {},
   "outputs": [],
   "source": [
    "for t in range(t_0, t_end):\n",
    "    results[t+1] = results[t] + annual_growth"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "signed-colleague",
   "metadata": {},
   "source": [
    "The values of `t` go from `t_0` to `t_end`, including the first but not the last.\n",
    "\n",
    "Inside the loop, we compute the population for the next year by adding the population for the current year and `annual_growth`. \n",
    "\n",
    "The last time through the loop, the value of `t` is 2015, so the last label in `results` is 2016.\n",
    "\n",
    "Here's what the results look like, compared to the estimates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "wrong-brooks",
   "metadata": {},
   "outputs": [],
   "source": [
    "results.plot(color='gray', label='model')\n",
    "plot_estimates()\n",
    "decorate(title='Constant growth model')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "automated-albany",
   "metadata": {},
   "source": [
    "From 1950 to 1990, the model does not fit the data particularly well, but after that, it's pretty good."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "unnecessary-million",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "This chapter is a first step toward modeling changes in world population growth during the last 70 years.\n",
    "\n",
    "We used Pandas to read data from a web page and store the results in a `DataFrame`.\n",
    "From the `DataFrame` we selected two `Series` objects and used them to compute absolute and relative errors.\n",
    "\n",
    "Then we computed average population growth and used it to build a simple model with constant annual growth.\n",
    "The model fits recent data pretty well; nevertheless, there are two reasons we should be skeptical:\n",
    "\n",
    "* There is no obvious mechanism that could cause population growth to be constant from year to year. Changes in population are determined by the fraction of people who die and the fraction of people who give birth, so we expect them to depend on the current population.\n",
    "\n",
    "* According to this model, world population would keep growing at the same rate forever, and that does not seem reasonable.\n",
    "\n",
    "In the next chapter we'll consider other models that might fit the data better and make more credible predictions."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "advanced-ivory",
   "metadata": {},
   "source": [
    "## Exercises"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hearing-today",
   "metadata": {
    "tags": []
   },
   "source": [
    "Here's the code from this chapter all in one place."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "terminal-reynolds",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "t_0 = census.index[0]\n",
    "t_end = census.index[-1]\n",
    "elapsed_time = t_end - t_0\n",
    "\n",
    "p_0 = census[t_0]\n",
    "p_end = census[t_end]\n",
    "\n",
    "total_growth = p_end - p_0\n",
    "annual_growth = total_growth / elapsed_time\n",
    "\n",
    "results = TimeSeries()\n",
    "results[t_0] = p_0\n",
    "\n",
    "for t in range(t_0, t_end):\n",
    "    results[t+1] = results[t] + annual_growth"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "organizational-memphis",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "results.plot(color='gray', label='model')\n",
    "plot_estimates()\n",
    "decorate(title='Constant growth model')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecological-welsh",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    "  Try fitting the model using data from 1970 to the present, and see if that does a better job.\n",
    "\n",
    "Suggestions: \n",
    "\n",
    "1. Define `t_1` to be 1970 and `p_1` to be the population in 1970.  Use `t_1` and `p_1` to compute annual growth, but use `t_0` and `p_0` to run the simulation. \n",
    "\n",
    "2. You might want to add a constant to the starting value to match the data better."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "rising-anger",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "false-handbook",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "political-loading",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "89bab9ad",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
